package com.trying.simpleioc.ioc;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.trying.simpleioc.util.ClassUtil;
import com.trying.simpleioc.util.PropertiesUtil;
import com.trying.simpleioc.util.ReflectionUtil;

public class BeanHelper {

	//‘类’和‘实例’的映射关系map
	private static final Map<Class<?>,Object> beanMap=new HashMap<Class<?>,Object>();
	
	
	public static void init(){
		
		Properties defaultProperties=PropertiesUtil.load("default.properties");
		if(defaultProperties==null){
			return;
		}
		String packageName=defaultProperties.getProperty("defaultPackage");
		Set<Class<?>> allClass=ClassUtil.getClassSet(packageName);
		
		for(Class<?> cls:allClass){
			Object instance=ReflectionUtil.newInstance(cls);
			beanMap.put(cls, instance);
		}
	}

	public static Map<Class<?>,Object> getBeanMap(){
		return beanMap;
	}
	
	public static <T> T getBean(Class<T> cla){
		if(!beanMap.containsKey(cla)){
			throw new RuntimeException("can not get bean instance by class:"+cla);
		}
		return (T) beanMap.get(cla);
	}
	
	
	
}
